import { BasePage, BasePageData } from "../common/core/BasePage";
import { field } from "../../modules/coreModule/data/DataLoader";
import { waitForLogin, userMgr } from "../../modules/userModule/managers/UserManager";
import { page, pageFunc } from "../common/PageBuilder";
import { DiscoverInterface } from "../../modules/discoverModule/discoverCommon";
import { UserInterface } from "../../modules/userModule/UserCommon";
import { pageMgr } from "../../modules/coreModule/managers/PageManager";
import { PostActivityPage } from "../post-activity/post-activityPage";
import { alertMgr } from "../../modules/coreModule/managers/AlertManager";
import { QueryPage } from "../common/partPages/QueryPage";
import { HomePage } from "../homepage/HomePagePage";
import { blockLoading, showLoading } from "../../modules/coreModule/managers/LoadingManager";
import { CoreLoading } from "../../modules/coreModule/CoreCommon";
import {appMgr} from "../../modules/coreModule/managers/AppManager";
import {UserPage} from "../common/partPages/UserPage";
import {UserDetailPage} from "../userDetail/UserDetailPage";
import {ShareAppPage} from "../common/partPages/SharePage";

const DefaultCount = 20;

class Data extends BasePageData {
  @field
  posts = [];
  @field
  allPosts = [];
  @field
  times = [];
  @field
  active = 'active';
  @field
  report = '';
  @field
  follow = '';
  @field
  activeOffset = 0;
  @field
  reportOffset = 0;
  @field
  followOffset = 0;
  @field
  searchOffset = 0;
  @field
  searchText = "";
  @field
  type = 0;
  @field
  showOverlay = false;
  @field
  showPicture = "";
  @field
  isEnd = false;
}

@page("discover", "发现")
export class DiscoverPage extends BasePage<Data> {
  data = new Data();

  public userPage: UserPage = new UserPage();
  public queryPage: QueryPage = new QueryPage(this.loadPosts.bind(this));
  public shareAppPage = new ShareAppPage();

  onLoad(e) {
    super.onLoad(e);
  }
  @pageFunc
  public onShow() {
    /*     this.setData({
          activeOffset: 0,
          reportOffset: 0,
          followOffset: 0
        }) */
        // console.log(appMgr().getToken())
    if(appMgr().getToken() != undefined){
      this.loadAllPosts();
    }else {
      alertMgr().showAlert("请先登录").then(() => {
        pageMgr().switch(HomePage).then();
      })
    }
  }

/*   @pageFunc
  public onReachBottom() {
    console.log("到底了")
    // this.queryPage.nextPage();
    // this.queryPage.refresh();
  } */

  @pageFunc
  public timeCounter(targetTime: number) {
    let date = Date.now();
    let distance = date - targetTime;
    if (distance < 1000 * 60) {
      return "刚刚"
    } else if (distance < 1000 * 60 * 60) {
      let num = distance / (1000 * 60);
      return Math.floor(num) + "分钟前"
    } else if (distance < 1000 * 60 * 60 * 24) {
      let num = distance / (1000 * 60 * 60);
      return Math.floor(num) + "小时前"
    } else if (distance < 1000 * 60 * 60 * 24 * 30) {
      let num = distance / (1000 * 60 * 60 * 24);
      return Math.floor(num) + "天前"
    } else if (distance < 1000 * 60 * 60 * 24 * 30 * 12) {
      let num = distance / (1000 * 60 * 60 * 24 * 30);
      return Math.floor(num) + "个月前"
    } else {
      let num = distance / (1000 * 60 * 60 * 24 * 365);
      return Math.floor(num) + "年前"
    }
  }
  @pageFunc
  onClickHide() {
    this.setData({ showOverlay: false });
  }
  @pageFunc
  showPicture(e) {
    console.log(e.currentTarget.dataset.image);
    this.setData({ showOverlay: true, showPicture: e.currentTarget.dataset.image })
  }
  @showLoading(CoreLoading.Mask)
  @blockLoading
  @waitForLogin
  private async loadPosts(queryParams, type, text) {
    let newParams = {};
    if (text != null) {
      newParams = {
        offset: queryParams.offset,
        count: DefaultCount,
        type: type != null ? type : this.data.type,
        text: text
      }
    }else {
      newParams = {
        offset: queryParams.offset,
        count: DefaultCount,
        type: type != null ? type : this.data.type,
      }
    }
    let posts = (await DiscoverInterface.GetPost({ ...newParams }))
    let postTime = [];
    let allPosts = posts.posts
    if(allPosts.length < DefaultCount){
      this.setData({isEnd: true});
    }
    posts.posts.forEach(posts => {
      postTime.push(this.timeCounter(posts.createdAt));
    });
    return { postTime, allPosts }
  }
  @pageFunc
  @waitForLogin
  public async loadAllPosts() {
    this.resetPage();
    let res = this.loadPosts(this.queryPage.queryParams, 0, null);
    this.setData({
      allPosts: (await res).allPosts,
      times: (await res).postTime,
      posts: (await res).allPosts,
      active: 'active',
      report: '',
      follow: '',
      type: 0
    })
  }
  @pageFunc
  @waitForLogin
  public async loadReportPosts() {
    this.resetPage();
    let res = this.loadPosts(this.queryPage.queryParams, 1, null);
    this.setData({
      allPosts: (await res).allPosts,
      times: (await res).postTime,
      posts: (await res).allPosts,
      active: '',
      report: 'active',
      follow: '',
      type: 1
    })
  }

  @pageFunc
  @waitForLogin
  public async loadFollowPosts() {
    this.resetPage();
    let res = this.loadPosts(this.queryPage.queryParams, 2, null);
    this.setData({
      allPosts: (await res).allPosts,
      times: (await res).postTime,
      posts: (await res).allPosts,
      active: '',
      report: '',
      follow: 'active',
      type: 2
    })
  }

  @waitForLogin
  public async loadMorePosts() {
    let res = this.loadPosts(this.queryPage.queryParams, this.data.type, null);
    let allPosts = this.data.allPosts;
    let allTime = this.data.times;
    (await res).allPosts.forEach(element => {
      allPosts.push(element);
    });
    (await res).postTime.forEach(element => {
      allTime.push(element);
    })
    this.setData({
      allPosts: allPosts,
      times: allTime,
      posts: allPosts,
      type: this.data.type
    })
    switch(this.data.type){
      case 0:
        this.setData({active: 'active', report:'', follow:''});
        break;
      case 1:
        this.setData({active: '', report:'active', follow:''});
        break;
      case 2:
        this.setData({active: '', report:'', follow:'active'});
        break;
    }
  }
  @pageFunc
  public contentChange(event) {
    this.setData({ searchText: event.detail })
    console.log(this.data.searchText)
  }
  @pageFunc
  @waitForLogin
  public async onSearch() {
    let res = this.loadPosts(this.queryPage.queryParams, this.data.type, this.data.searchText);
    this.setData({
      allPosts: (await res).allPosts,
      times: (await res).postTime,
      posts: (await res).allPosts,
    })
  }
  /*   public async followUser(openid, follow){
      let dataInit = {
        openid,
        follow
      }
      let result = (await UserInterface.FollowUser({...dataInit}));
      console.log()
    } */
  @pageFunc
  @waitForLogin
  public follow(e) {
    let openid = e.currentTarget.dataset.id;
    let followString = e.currentTarget.dataset.follow;
    let follow = true;
    if (followString != 'true') {
      follow = false;
    }
    UserInterface.FollowUser({ openid, follow }).then();
    let index = 0;
    let postsCopy = this.data.posts;
    this.data.posts.forEach(data => {
      if (data.userId == openid) {
        postsCopy[index].isFollowed = !postsCopy[index].isFollowed;
        this.setData({
          posts: postsCopy
        }).then();
      }
      index++;
    })
    console.log(this.data.posts);
    if (follow == true) {
      alertMgr().showAlert("关注成功").then();
    } else {
      alertMgr().showAlert("取消关注成功").then();
    }
  }
  @pageFunc
  public toPost() {
    pageMgr().push(PostActivityPage).then();
  }
  @pageFunc
  @waitForLogin
  public loadMore(){
    this.nextPage(); this.queryPage.refresh();
    this.loadMorePosts();
  }
  @waitForLogin
  public resetPage() {
    this.queryPage.queryParams.offset = 0;
    this.setData({isEnd: false});
  }
  @waitForLogin
  public nextPage() {
		this.queryPage.queryParams.offset += DefaultCount;
	}

  @pageFunc
  public showUserDetail(e) {
    pageMgr().push(UserDetailPage, {id: e.target.dataset.id})
  }
  /* 	private async loadMessages(queryParams) {
      const messages: Message[] = (await MessageInterface.GetMessages(queryParams))
        .messages.map(m => DataLoader.load(Message, m));
      // 按时间降序排列
      messages.sort((ma, mb) => mb.createdAt - ma.createdAt);
      const unreadCnt = messages.filter(m => m.status == MessageStatus.Unread).length;
      await this.setData({messages, unreadCnt});
    } */
}
